package io.github.lostblackknight;

import org.junit.jupiter.api.Test;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.Arrays;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author chensixiang chensixiang1234@gmail.com
 */
public class VerifyCode {

    static JedisPool jedisPool = new JedisPool("192.168.255.133", 6379);

    @Test
    public void test1() {
        sendCode("17735746553");
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void test2() {
        verifyCode("17735746553", "511358");
    }

    public static void verifyCode(String phone, String code) {
        Jedis jedis = jedisPool.getResource();
        String codeKey = "VerifyCode" + phone + ":code";
        String s = jedis.get(codeKey);
        if (code.equals(s)) {
            System.out.println("成功");
        } else {
            System.out.println("失败");
        }
    }

    public static void sendCode(String phone) {
        Jedis jedis = jedisPool.getResource();

        String countKey = "VerifyCode" + phone + ":count";
        String codeKey = "VerifyCode" + phone + ":code";
        String redisCount = jedis.get(countKey);
        if (redisCount == null) {
            // 没有发送，设为1，添加过期时间
            jedis.setex(countKey, 24L * 60L * 60L, "1");
        } else if (Integer.parseInt(redisCount) <= 2) {
            jedis.incr(countKey);
        } else if (Integer.parseInt(redisCount) > 2) {
            System.out.println("今天的发送次数已经超过三次");
            jedis.close();
            return;
        }
        String code = getCode();
        System.out.println(code);
        jedis.setex(codeKey, 120L, code);
        jedis.close();
    }

    public static String getCode() {
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            int num = random.nextInt(10);
            code.append(num);
        }
        return code.toString();
    }
}
